package brc.syntacticTree;

import java.io.IOException;
import java.io.Writer;

public class UnaryNumericTreeNode implements TypedTreeNode {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4386419868221510656L;
	private TypedTreeNode child;
	private Modifier modifier;

	public UnaryNumericTreeNode(TypedTreeNode child, Modifier modifier) {
		if (child == null){
			throw new NullPointerException("The child must be passed pass parameters");
		}
		this.child = child;
		
		if (modifier == null){
			this.modifier = Modifier.None;
		}
		else {
			this.modifier = modifier;
		}
	}

	public TypedTreeNode getChild() {
		return child;
	}
	public Modifier getModifier() {
		return modifier;
	}

	@Override
	public void writeAssembly(Writer writer) throws IOException {
		// write operation
		this.child.writeAssembly(writer);
		if (this.modifier == Modifier.Minus) {
			writer.write("ineg\r\n");
		}
	}

	@Override
	public void semanticCheck() throws SemanticException {
		this.child.semanticCheck();
		if (this.child.getType() != TypedTreeNode.TIPO_NUMERO) {
			throw new SemanticException("Only a number can have a negative value");
		}
	}
	
	public TypedTreeNode simplify() {
		switch (this.modifier) {
		case Minus:
			if (this.child instanceof ConstantNumberNode) {
				return new ConstantNumberNode(-((ConstantNumberNode)this.child).getNumber());
			}
			break;
		case Plus:
			if (this.child instanceof ConstantNumberNode) {
				 return this.child;
			}
			break;
		default:
			return this.child;
		}
		return this;
	}

	@Override
	public int getType() {
		return this.child.getType();
	}
	
	public enum Modifier {
		Plus,
		Minus,
		None
	}
}
